package com.byb.server.web.rest;


import com.byb.server.service.RateService;
import com.byb.server.service.dto.*;

import com.codahale.metrics.annotation.Timed;
import com.byb.server.service.ProductService;
import com.byb.server.web.rest.util.HeaderUtil;
import com.byb.server.web.rest.util.PaginationUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import io.swagger.annotations.ApiParam;
import io.github.jhipster.web.util.ResponseUtil;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.net.URI;
import java.net.URISyntaxException;

import java.util.Collection;

import java.util.List;
import java.util.Optional;


/**
 * REST controller for managing Product.
 */
@RestController
@RequestMapping("/api")
public class ProductResource {

    private final Logger log = LoggerFactory.getLogger(ProductResource.class);

    private static final String ENTITY_NAME = "product";

    private final ProductService productService;



    public ProductResource(ProductService productService) {
        this.productService = productService;

    }

    /**
     * POST  /products : Create a new product.
     *
     * @param productDTO the productDTO to create
     * @return the ResponseEntity with status 201 (Created) and with body the new productDTO, or with status 400 (Bad Request) if the product has already an ID
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PostMapping("/products")
    @Timed
    public ResponseEntity<ProductDTO> createProduct(@RequestBody ProductDTO productDTO) throws URISyntaxException {
        log.debug("REST request to save Product : {}", productDTO);
        if (productDTO.getId() != null) {
            return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert(ENTITY_NAME, "idexists", "A new product cannot already have an ID")).body(null);
        }
        ProductDTO result = productService.save(productDTO);
        return ResponseEntity.created(new URI("/api/products/" + result.getId()))
            .headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString()))
            .body(result);
    }

    /**
     * PUT  /products : Updates an existing product.
     *
     * @param productDTO the productDTO to update
     * @return the ResponseEntity with status 200 (OK) and with body the updated productDTO,
     * or with status 400 (Bad Request) if the productDTO is not valid,
     * or with status 500 (Internal Server Error) if the productDTO couldn't be updated
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PutMapping("/products")
    @Timed
    public ResponseEntity<ProductDTO> updateProduct(@RequestBody ProductDTO productDTO) throws URISyntaxException {
        log.debug("REST request to update Product : {}", productDTO);
        if (productDTO.getId() == null) {
            return createProduct(productDTO);
        }
        ProductDTO result = productService.save(productDTO);
        return ResponseEntity.ok()
            .headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, productDTO.getId().toString()))
            .body(result);
    }

    /**
     * GET  /products : get all the products.
     *
     * @param pageable the pagination information
     * @return the ResponseEntity with status 200 (OK) and the list of products in body
     */
    @GetMapping("/products")
    @Timed
    public ResponseEntity<List<ProductDTO>> getAllProducts(@ApiParam Pageable pageable) {
        log.debug("REST request to get a page of Products");
        Page<ProductDTO> page = productService.findAll(pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/products");
        return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
    }

    /**
     * GET  /products/:id : get the "id" product.
     *
     * @param id the id of the productDTO to retrieve
     * @return the ResponseEntity with status 200 (OK) and with body the productDTO, or with status 404 (Not Found)
     */
    @GetMapping("/products/{id}")
    @Timed
    public ResponseEntity<ProductDTO> getProduct(@PathVariable Long id) {
        log.debug("REST request to get Product : {}", id);
        ProductDTO productDTO = productService.findOne(id);
        return ResponseUtil.wrapOrNotFound(Optional.ofNullable(productDTO));
    }

    /**
     * DELETE  /products/:id : delete the "id" product.
     *
     * @param id the id of the productDTO to delete
     * @return the ResponseEntity with status 200 (OK)
     */
    @DeleteMapping("/products/{id}")
    @Timed
    public ResponseEntity<Void> deleteProduct(@PathVariable Long id) {
        log.debug("REST request to delete Product : {}", id);
        productService.delete(id);
        return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build();
    }

    /**
     * SEARCH  /_search/products?query=:query : search for the product corresponding
     * to the query.
     *
     * @param query the query of the product search
     * @param pageable the pagination information
     * @return the result of the search
     */
    @GetMapping("/_search/products")
    @Timed
    public ResponseEntity<List<ProductDTO>> searchProducts(@RequestParam String query, @ApiParam Pageable pageable) {
        log.debug("REST request to search for a page of Products for query {}", query);
        Page<ProductDTO> page = productService.search(query, pageable);
        HttpHeaders headers = PaginationUtil.generateSearchPaginationHttpHeaders(query, page, "/api/_search/products");
        return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
    }

    /**
     * GET  /ProductDetail/:id : get the "id" ProductDetail.
     *
     * @param id the id of the ProductDetail to retrieve
     * @return the ResponseEntity with status 200 (OK) and with body the ProductDetailsDTO, or with status 404 (Not Found)
     */
    @GetMapping("/productDetail")
    @Timed
    public ResponseEntity<ProductDetail> getProductDetailsDTO(@RequestParam Long id, @RequestParam String age, @RequestParam Integer premiumPaymentPeriod, @RequestParam String sexName, @RequestParam  Integer payment, @RequestParam Integer orderByState, @RequestParam(value = "query",required = false) String query, @ApiParam Pageable pageable) {
        log.debug("REST request to get ProductDetailsDTO : {}", id);

//        ProductDetail productDetail = productService.findOneById(id, age, premiumPaymentPeriod, sexName, payment, orderByState, gson.fromJson(query, new TypeToken<Collection<Long>>(){}.getType()), pageable);
//        if(productDetail==null){
//            return ResponseEntity.ok(null);
//        }


       // return ResponseUtil.wrapOrNotFound(Optional.ofNullable(productDetail));
//        Gson gson=new Gson();
//        ProductDetail productDetail = productService.findById(id, age, premiumPaymentPeriod, sexName, payment, orderByState, gson.fromJson(query, new TypeToken<Collection<Long>>(){}.getType()), pageable,true);
        ProductDetail productDetail = productService.findByIdRebuild(id, age, premiumPaymentPeriod, sexName, payment, orderByState,query, false,pageable);
        return Optional.ofNullable(productDetail).map(response -> ResponseEntity.ok().headers(new HttpHeaders()).body(response))
            .orElse(ResponseEntity.ok().headers(new HttpHeaders()).body(null));
    }


    @GetMapping("/productDetail/score")
    @Timed
    public ResponseEntity<ProductDetailScoreDTO> getProductDetailScore(@RequestParam Long id,@RequestParam String age,@RequestParam Integer premiumPaymentPeriod,@RequestParam String sexName,@RequestParam  Integer payment,@RequestParam Integer orderByState,@RequestParam(value = "query",required = false)  String query,@ApiParam Pageable pageable){
        log.debug("REST request to get ProductDeatailScore : {}", id);
//        Gson gson=new Gson();
//        boolean flag=false;
//        ProductDetail productDetail = productService.findById(id, age, premiumPaymentPeriod, sexName, payment, orderByState, gson.fromJson(query, new TypeToken<Collection<Long>>(){}.getType()), pageable,flag);
//        if(productDetail==null){
//            return  new ResponseEntity<>(HttpStatus.NOT_FOUND);
//        }
        ProductDetailScoreDTO productDetailScoreDTO = productService.findByIdDetailScore(id, age,premiumPaymentPeriod,sexName,payment,orderByState,query,pageable);
        return ResponseUtil.wrapOrNotFound(Optional.ofNullable(productDetailScoreDTO));
    }

    @DeleteMapping("/api/util-delect-product-info/{id}")
    @Timed
    public ResponseEntity<Void> delectPrById(@PathVariable("id") Long id){
        log.debug("REST request to delete Product All Info: {}", id);
        productService.delectProdcutAllInfo(id);
        return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build();
    }
}
